package com.lxd.bank.listener;


import com.lxd.bank.pojo.BankMqLog;
import com.lxd.bank.pojo.OrderMqLog;
import com.lxd.bank.service.BankService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

@Component
@Slf4j
public class RabbitMqListener {

    @Autowired
    private BankService bankService;

    /*@RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "consume.queue"),
            exchange = @Exchange(name = "consume.fanout", type = ExchangeTypes.FANOUT)
    ))*/
    @RabbitListener(queues = "consume.queue")
    @Transactional
    public void consumeFanoutListener(OrderMqLog msg, Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("consume fanout listener：【" + msg + "】");
            List<BankMqLog> bankMqLogs= bankService.selectMqLogByTid(msg.getId());
            if (!bankMqLogs.isEmpty())
                throw new RuntimeException("重复操作account");
            bankService.updateAccount(msg);
            bankService.insertMqLog(msg);
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            channel.basicReject(deliveryTag,false);
            e.printStackTrace();
        }

    }

}
